#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
图像处理工具类
提供图像编码、解码、处理等功能
"""

import base64
import os

def encode_image_to_base64(image_path):
    """将图片编码为Base64"""
    try:
        if not os.path.exists(image_path):
            return None
            
        with open(image_path, "rb") as image_file:
            encoded = base64.b64encode(image_file.read()).decode('utf-8')
            return f"data:image/jpeg;base64,{encoded}"
    except Exception as e:
        print(f"图片编码失败: {e}")
        return None

def get_latest_images_from_folders(folders, count_per_folder=1):
    """从指定文件夹中获取最新的图片文件
    
    Args:
        folders: 文件夹列表
        count_per_folder: 每个文件夹获取的图片数量
    
    Returns:
        图片文件列表，包含路径和Base64编码
    """
    import glob
    images = []
    
    for folder in folders:
        if not os.path.exists(folder):
            continue
            
        files = glob.glob(f"{folder}/*.jpg")
        # 按修改时间排序，获取最新的图片
        files.sort(key=os.path.getmtime, reverse=True)
        
        for file in files[:count_per_folder]:
            base64_image = encode_image_to_base64(file)
            if base64_image:
                images.append({
                    "path": file.replace("\\", "/"),
                    "name": os.path.basename(file),
                    "folder": folder,
                    "mtime": os.path.getmtime(file),
                    "base64": base64_image
                })
    
    # 按时间排序，返回最新的图片
    images.sort(key=lambda x: x["mtime"], reverse=True)
    return images